package com.example.dao;

import com.example.util.DBUtil;
import java.sql.*;
import java.time.LocalDateTime;

public class PasswordResetDao {
    
    /**
     * 创建密码重置令牌
     */
    public void createResetToken(int userId, String token, Timestamp expiresAt) throws SQLException {
        String sql = "INSERT INTO tb_password_reset (user_id, token, expires_at) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setInt(1, userId);
            stmt.setString(2, token);
            stmt.setTimestamp(3, expiresAt);
            stmt.executeUpdate();
        }
    }
    
    /**
     * 根据令牌查找重置记录
     */
    public PasswordResetToken findToken(String token) throws SQLException {
        String sql = "SELECT * FROM tb_password_reset WHERE token = ? AND used = FALSE AND expires_at > NOW()";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, token);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    PasswordResetToken resetToken = new PasswordResetToken();
                    resetToken.setId(rs.getInt("id"));
                    resetToken.setUserId(rs.getInt("user_id"));
                    resetToken.setToken(rs.getString("token"));
                    resetToken.setExpiresAt(rs.getTimestamp("expires_at"));
                    resetToken.setUsed(rs.getBoolean("used"));
                    resetToken.setCreatedAt(rs.getTimestamp("created_at"));
                    return resetToken;
                }
            }
        }
        return null;
    }
    
    /**
     * 标记令牌为已使用
     */
    public void markTokenAsUsed(int tokenId) throws SQLException {
        String sql = "UPDATE tb_password_reset SET used = TRUE WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setInt(1, tokenId);
            stmt.executeUpdate();
        }
    }
    
    /**
     * 删除用户的所有重置令牌
     */
    public void deleteTokensForUser(int userId) throws SQLException {
        String sql = "DELETE FROM tb_password_reset WHERE user_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setInt(1, userId);
            stmt.executeUpdate();
        }
    }
    
    /**
     * 根据用户ID和邮箱查找用户
     */
    public int findUserIdByEmail(String email) throws SQLException {
        String sql = "SELECT id FROM tb_user WHERE email = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, email);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt("id");
                }
            }
        }
        return -1; // 用户不存在
    }
    
    /**
     * 更新用户密码
     */
    public void updatePassword(int userId, String newPassword) throws SQLException {
        String sql = "UPDATE tb_user SET password = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, newPassword);
            stmt.setInt(2, userId);
            stmt.executeUpdate();
        }
    }
    
    public static class PasswordResetToken {
        private int id;
        private int userId;
        private String token;
        private Timestamp expiresAt;
        private boolean used;
        private Timestamp createdAt;
        
        // Getters and setters
        public int getId() { return id; }
        public void setId(int id) { this.id = id; }
        
        public int getUserId() { return userId; }
        public void setUserId(int userId) { this.userId = userId; }
        
        public String getToken() { return token; }
        public void setToken(String token) { this.token = token; }
        
        public Timestamp getExpiresAt() { return expiresAt; }
        public void setExpiresAt(Timestamp expiresAt) { this.expiresAt = expiresAt; }
        
        public boolean isUsed() { return used; }
        public void setUsed(boolean used) { this.used = used; }
        
        public Timestamp getCreatedAt() { return createdAt; }
        public void setCreatedAt(Timestamp createdAt) { this.createdAt = createdAt; }
    }
}